﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainPage.xaml.cs" company="Simon Carpentier">
//   Microsoft Reciprocal License (Ms-RL)
// </copyright>
// <summary>
//   Defines the MainPage type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace VinoCellar
{
    using System;
    using System.Diagnostics;
    using System.IO.IsolatedStorage;
    using System.Windows;
    using System.Windows.Controls;

    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Tasks;

    using VinoCellar.Model;

    using WP7_Barcode_Library;

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.DataContext = App.ViewModel;

            // Set the data context of the listbox control to the sample data
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoAddToLibrary"))
            {
                cbAutoAddToLibrary.IsChecked = IsolatedStorageSettings.ApplicationSettings["AutoAddToLibrary"] as bool?;
            }
        }

        private void btnSnap_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.UPC_EAN;

                var bBypassCamera = false;

                if (bBypassCamera == true) //Use Barcode Sample Chooser "Task" if bypass camera setting is active (Emulator/demo mode)
                {
                }
                else //Use BarcodeManager to start camera and scan image
                {
                    WP7BarcodeManager.ScanBarcode(BarcodeResults_Finished); //Provide callback method
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error processing image.", ex);
            }
        }

        /// <summary>
        /// Callback method that processes results returned by the WP7BarcodeManager. Results are also stored at WP7BarcodeManager.LastCaptureResults.
        /// </summary>
        /// <param name="BCResults">Object that holds all the results of processing the barcode. Results are also stored at WP7BarcodeManager.LastCaptureResults.</param>
        public void BarcodeResults_Finished(BarcodeCaptureResult BCResults)
        {
            try
            {
                if (BCResults.State == WP7_Barcode_Library.CaptureState.Success)
                {
                    txtUPC.Text = BCResults.BarcodeText;
                    this.ShowDetails(BCResults.BarcodeText);
                }
                else
                {
                    Debug.WriteLine(BCResults.ErrorMessage);
                    MessageBox.Show(BCResults.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Barcode Processing Error: {0}", ex.Message));
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGetDetails_Click(object sender, RoutedEventArgs e)
        {
            if (!Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable)
            {
                MessageBox.Show(
                    "Network is required for this operation. Please, connect your phone and try again.");
                return;
            }

            if (txtUPC.Text == string.Empty)
            {
                MessageBox.Show("Please enter a valid UPC code");
                return;
            }
                    
            this.ShowDetails(txtUPC.Text);
        }

        private void ShowDetails(string upc)
        {
            NavigationService.Navigate(new Uri(string.Format("/New.xaml?upc={0}", upc), UriKind.RelativeOrAbsolute));
        }

        private void ShowDetails(int id)
        {
            NavigationService.Navigate(new Uri(string.Format("/Wine.xaml?id={0}", id), UriKind.RelativeOrAbsolute));
        }

        private void hlExample_Click(object sender, RoutedEventArgs e)
        {
            txtUPC.Text = "8014629140018";
        }

        private void cbAutoAddToLibrary_Checked(object sender, RoutedEventArgs e)
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (!settings.Contains("AutoAddToLibrary"))
            {
                settings.Add("AutoAddToLibrary", ((CheckBox)sender).IsChecked);
            }
            else
            {
                settings["AutoAddToLibrary"] = ((CheckBox)sender).IsChecked;
            }

            settings.Save();
        }

        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.ShowDetails(((WineItem)((StackPanel)sender).DataContext).WineItemId);
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask webbrowser = new WebBrowserTask();
            webbrowser.Uri = new Uri("http://vinocellar.codeplex.com");
            webbrowser.Show();
        }
    }
}